class Solution:
    def findOrder(self, numCourses, prerequisites):
        pres = [set() for _ in range(numCourses)]
        for course, pre in prerequisites:
            pres[course].add(pre)

        # judge loop condition        
        already = [False] * numCourses
        acc = set()
        def find(course):
            if course in acc: raise Exception("loop")
            acc.add(course)
            already[course]=True
            for p in pres[course]:
                find(p)
            acc.remove(course)
        for course in range(numCourses):
            if not already[course]:
                try:
                    find(course)
                except Exception as e:
                    return []
        
        already = [False] * numCourses
        order = []
        def study(course):
            if already[course]: return
            for p in pres[course]:
                study(p)
            order.append(course)
            already[course] = True
        for course in range(numCourses):
            if not already[course]:
                study(course)
        return order

print(Solution().findOrder(4, [[1,0],[2,0],[3,1],[3,2]]))